package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Slf4j
@RequiredArgsConstructor
@Service
public class TaskServiceImpl implements TaskService {


    private final TaskinfoMapper taskinfoMapper;

    private final TaskinfoLogsMapper taskinfoLogsMapper;

    private final CacheService cacheService;


    /**
     * 添加任务
     *
     * @param task 任务对象
     * @return 任务id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public long addTask(Task task) {
        // 1、添加数据到 数据库
        boolean success = addTaskToDb(task);
        // 2、存redis
        if (success) {
            addTaskToRedis(task);
        }

        return task.getTaskId();
    }


    /**
     * 取消任务
     *
     * @param taskId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelTask(long taskId) {
        boolean flag = false;
        // 删除任务，更新任务日志
        Task task = updateDbTask(taskId, ScheduleConstants.CANCELLED);
        if (task != null) {
            removeTaskFromCache(task);
            flag = true;
        }
        return flag;
    }


    /**
     * 按照类型和优先级来拉取任务
     *
     * @param type
     * @param priority
     * @return 返回任务对象
     */
    @Override
    public Task poll(int type, int priority) {
        Task task = null;
        try {
            String key = type + "_" + priority;
            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (StringUtils.isNotBlank(task_json)) {
                task = JSON.parseObject(task_json, Task.class);
                //更新数据库信息
                updateDbTask(task.getTaskId(), ScheduleConstants.EXECUTED);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("poll task exception");
            throw new RuntimeException();
        }

        return task;
    }


    /**
     * 定时任务，将未来数据(zset) 同步到当前数据(list) 中
     */
    @Scheduled(fixedDelay = 1000 * 60) //TODO：需要了解 2024/10/21 cron = "0 */1 * * * ?"
    public void refresh() {

        String token = null;
        try {
            token = cacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);

            if (StringUtils.isNotBlank(token)) {
                log.info("未来数据定时刷新---定时任务");
                // 1、拿到未来数据(zset)集合中的key
                Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");

                for (String futureKey : futureKeys) { // future_100_50

                    // 拿到当前的数据
                    String topicKey = ScheduleConstants.TOPIC + futureKey.split(ScheduleConstants.FUTURE)[1];

                    // 按照key和分值查询符合条件的数据 (过期数据)
                    Set<String> tasks = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());

                    // 同步数据 将未来数据(zset) 转移到当前数据中(list)
                    if (!tasks.isEmpty()) {
                        cacheService.refreshWithPipeline(futureKey, topicKey, tasks);
                        log.info("成功的将" + futureKey + "刷新到了" + topicKey);
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 解锁
            cacheService.unlock("FUTURE_TASK_SYNC",token);
        }




    }


    /**
     * 数据库任务定时同步redis(zset)
     */
    @Scheduled(fixedDelay = 1000 * 60 * 5)
    @PostConstruct
    public void reloadData() {
        // 清理缓存中的数据 list zset
        clearCache();
        // 查询任务表 条件 小于未来5分钟的数据
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery()
                .lt(Taskinfo::getExecuteTime, calendar.getTime()));

        // 把任务添加到redis(zset)
        if (taskinfoList != null && taskinfoList.size() > 0) {
            for (Taskinfo taskinfo : taskinfoList) {
                Task task = new Task();
                BeanUtils.copyProperties(taskinfo, task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskToRedis(task);
            }
        }
        log.info("数据库的任务同步到redis");
    }

    /**
     * 清理缓存中的数据
     * 清理当前数据(list) 未来数据(zset)
     */
    private void clearCache() {

        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(topicKeys);
        cacheService.delete(futureKeys);
    }

    /**
     * 删除redis中的数据
     *
     * @param task
     */
    private void removeTaskFromCache(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();

        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            // 删除当前的任务 从list中删除
            cacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(task));
        } else {
            // 删除未来的任务 从zset删除
            cacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(task));
        }
    }

    /**
     * 更新任务状态 删除任务 修改任务日志
     *
     * @param taskId
     * @param cancelled
     * @return
     */
    private Task updateDbTask(long taskId, int cancelled) {
        Task task = null;
        try {
            // 删除任务
            taskinfoMapper.deleteById(taskId);

            // 修改任务日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(cancelled);
            taskinfoLogsMapper.updateById(taskinfoLogs);

            task = new Task();
            BeanUtils.copyProperties(taskinfoLogs, task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        } catch (BeansException e) {
            log.error("task cancel exception taskid={}", taskId);
            throw new RuntimeException(e);
        }

        return task;
    }

    /**
     * 添加任务到redis中
     *
     * @param task
     */
    private void addTaskToRedis(Task task) {
        String key = task.getTaskType() + "_" + task.getPriority();

        // 获取5分钟后的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long nextScheduleTime = calendar.getTimeInMillis();

        if (task.getExecuteTime() <= System.currentTimeMillis()) {
            // 2.1、如果任务的执行时间小于当前时间，存入list
            cacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if (task.getExecuteTime() <= nextScheduleTime) {
            // 2.2、如果任务的执行时间大于当前时间 && 小于等于预设时间(未来5分钟)，存入zset
            cacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime());
        }
    }

    /**
     * 添加任务到数据库中
     *
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {
        boolean flag = false;
        try {
            // 1、保存到taskinfo表中
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task, taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);

            // 设置任务id
            task.setTaskId(taskinfo.getTaskId());

            // 2、保存到taskinfo_logs表中
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }
        return flag;
    }
}
